package com.jxm.security.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.jxm.security.common.R;
import com.jxm.security.common.TokenUtils;
import com.jxm.security.entity.User;
import com.jxm.security.pojo.SysUser;
import com.jxm.security.service.LoginService;
import com.sun.org.apache.bcel.internal.generic.NEW;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;

/**
 * @Author: jxm
 * @Description:
 * @Date: 2022/5/24 21:38
 * @Version: 1.0
 */
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Autowired
    AuthenticationManager authenticationManager;
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 用户认证
     * @param user
     * @return
     */
    @Override
    public R login(User user) {

        //AuthenticationManager authenticate进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //如果认证没通过，给出对应的提示
        if(ObjectUtils.isEmpty(authenticate)){
            return R.error().message("用户认证失败,用户名或密码错误");
        }
        //如果认证通过了，使用userid生成一个jwt jwt存入ResponseResult返回
        SysUser loginUser = (SysUser) authenticate.getPrincipal();
        String id = loginUser.getUser().getId();
        String token = TokenUtils.createToken(id);
        //把完整的用户信息存入redis userid作为key
        String jsonString = JSONObject.toJSONString(loginUser);
        redisTemplate.opsForValue().set("login"+id,jsonString);
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        return R.ok().data(map);
    }
}
